<template>
  <div class="app-container">
	  <el-tabs v-model="queryParams.attrType" class="center-tabs" type="card" @tab-click="tabClick">
		  <el-tab-pane v-for="dict in um_attr_type" :label="dict.label" :name="dict.value">
		  </el-tab-pane>
	  </el-tabs>


    <el-row :gutter="10" class="mb8" v-if="queryParams.attrType !== 'auth'">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['um:umAttrConf:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['um:umAttrConf:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['um:umAttrConf:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['um:umAttrConf:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="umAttrConfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置类型" align="center" prop="attrType" v-if="columnVisible('attrType')">
        <template #default="scope">
          <dict-tag :options="um_attr_type" :value="scope.row.attrType"/>
        </template>
      </el-table-column>
      <el-table-column label="显示类型" align="center" prop="viewType" v-if="columnVisible('viewType')">
        <template #default="scope">
          <dict-tag :options="um_attr_view_type" :value="scope.row.viewType"/>
        </template>
      </el-table-column>
      <el-table-column label="属性代码" align="center" prop="attrCode" v-if="columnVisible('attrCode')"/>
      <el-table-column label="属性名称" align="center" prop="attrName" v-if="columnVisible('attrName')"/>
			<el-table-column label="字典类型" align="center" prop="dictType" v-if="columnVisible('dictType')" width="210"/>
      <el-table-column label="排序" align="center" prop="sort" v-if="columnVisible('sort')"/>
			<el-table-column label="是否择偶标准" align="center" prop="isStandard" v-if="columnVisible('isStandard') && (queryParams.attrType === 'base' || queryParams.attrType === 'detail')" >
				<template #default="scope">
<!--					<dict-tag :options="sys_yes_no" :value="scope.row.isStandard"/>-->
					<el-switch v-model="scope.row.isStandard" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row,'isStandard','开启','停用')"></el-switch>
				</template>
			</el-table-column>
      <el-table-column label="备注" align="center" prop="remark" v-if="columnVisible('remark')"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['um:umAttrConf:query']" v-noPermi="['um:umAttrConf:edit']">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['um:umAttrConf:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['um:umAttrConf:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改用户属性配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="umAttrConfRef" :model="form" :rules="rules" label-width="80px" :disabled="!isInsert && !isEdit">
        <el-form-item label="配置类型" prop="attrType">
          <el-select v-model="form.attrType" placeholder="请选择" >
            <el-option v-for="dict in um_attr_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性代码" prop="attrCode">
          <el-input v-model="form.attrCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="属性名称" prop="attrName">
          <el-input v-model="form.attrName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="显示类型" prop="viewType">
          <el-select v-model="form.viewType" placeholder="请选择" @change="viewTypeChange">
            <el-option v-for="dict in um_attr_view_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
	        <el-button type="primary" size="small" @click="handleViewExample" style="margin-left: 2px">示例</el-button>

	        <span style="font-size: 12px;line-height: 1.4;color: #dc9d5e">手机端仅支持：文本框、文本域、数字输入、单选框、下拉框、复选框、日期控件、图片上传</span>
        </el-form-item>
	      <el-form-item label="字典类型" prop="dictType" v-if="!form.dictTypeDisable">
		      <el-select v-model="form.dictType" placeholder="请选择" :disabled="form.dictTypeDisable">
			      <el-option v-for="dict in dictOptions" :key="dict.dictType" :label="dict.dictName" :value="dict.dictType"></el-option>
		      </el-select>
	      </el-form-item>
	    <el-form-item label="排序" prop="sort">
	    	<el-input-number v-model="form.sort" placeholder="请输入" />
				</el-form-item>
				<el-form-item label="是否择偶标准" prop="isStandard">
					<el-radio-group v-model="form.isStandard" >
						<el-radio v-for="dict in sys_yes_no" :key="dict.value" :label="parseInt(dict.value)">{{dict.label}}</el-radio>
					</el-radio-group>
	    </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer v-if="isEdit || isInsert">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

	  <el-dialog title="显示类型示例" v-model="visible" width="800px" top="5vh" append-to-body>
		  <el-form>
			  <el-row>
				  <el-col :span="type.value == 'editor'?24:12" v-for="type in viewType">
					  <el-form-item :label="type.label" v-model="type.test">
						  <el-input clearable v-if="type.value == 'input'" v-model="type.test"/>
						  <el-input-number clearable v-else-if="type.value == 'inputNumber'" v-model="type.test"/>
						  <el-input clearable type="textarea" v-else-if="type.value == 'textarea'" v-model="type.test"/>
						  <el-select clearable v-else-if="type.value == 'select'" v-model="type.test">
							  <el-option label="选项1" value="1"/>
							  <el-option label="选项2" value="2"/>
							  <el-option label="选项3" value="3"/>
						  </el-select>
						  <el-radio-group clearable v-else-if="type.value == 'radio'" v-model="type.test">
							  <el-radio label="1">选项1</el-radio>
							  <el-radio label="2">选项2</el-radio>
							  <el-radio label="3">选项3</el-radio>
						  </el-radio-group>
						  <el-checkbox-group clearable v-else-if="type.value == 'checkbox'" v-model="type.test">
							  <el-checkbox label="1">选项1</el-checkbox>
							  <el-checkbox label="2">选项2</el-checkbox>
							  <el-checkbox label="3">选项3</el-checkbox>
						  </el-checkbox-group>
						  <el-date-picker clearable v-else-if="type.value == 'date'" type="date" value-format="YYYY-MM-DD" placeholder="请选择" v-model="type.test"/>
						  <el-time-picker clearable v-else-if="type.value == 'time'" value-format="HH:mm:ss" placeholder="请选择" v-model="type.test"/>
						  <el-date-picker clearable v-else-if="type.value == 'datetime'" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" v-model="type.test"/>
						  <el-time-select clearable v-else-if="type.value == 'timeSelect'" start="06:00" step="00:30" end="23:00" placeholder="请选择" v-model="type.test"/>
						  <image-upload v-else-if="type.value == 'imageUpload'" v-model="type.test"/>
						  <file-upload v-else-if="type.value == 'fileUpload'" v-model="type.test"/>
						  <editor v-else-if="type.value == 'editor'" :min-height="192" v-model="type.test"/>
					  </el-form-item>
				  </el-col>
			  </el-row>
		  </el-form>
	  </el-dialog>
  </div>
</template>

<script setup name="UmAttrConf">
import { listUmAttrConf, getUmAttrConf, delUmAttrConf, addUmAttrConf, updateUmAttrConf } from "@/api/um/umAttrConf";
import { optionselect } from "@/api/sys/dict/type";

const { proxy } = getCurrentInstance();
const { um_attr_view_type, um_attr_type, sys_yes_no } = proxy.useDict('um_attr_view_type', 'um_attr_type', 'sys_yes_no');

const umAttrConfList = ref([]);
const isEdit = ref(false);
const isInsert = ref(false);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const visible = ref(false);

const viewType = ref([
	{label: "文本框", value: "input", "test": null},
	{label: "数字输入", value: "inputNumber", "test": null},
	{label: "文本域", value: "textarea", "test": null},
	{label: "下拉框", value: "select", "test": null},
	{label: "单选框", value: "radio", "test": null},
	{label: "复选框", value: "checkbox", "test": []},
	{label: "日期控件", value: "date", "test": null},
	{label: "时间控件", value: "time", "test": null},
	{label: "日期时间", value: "datetime", "test": null},
	{label: "时间选择", value: "timeSelect", "test": null},
	{label: "图片上传", value: "imageUpload", "test": null},
	{label: "文件上传", value: "fileUpload", "test": null},
	{label: "富文本", value: "editor", "test": null}
]);

// 列显隐信息(able表示列是否可用，visible用于用户控制显隐)
const columns = ref([
  { label: `id`, able:false, visible: false, key: 'id' },
  { label: `配置类型`, able:true, visible: true, key: 'attrType' },
  { label: `显示类型`, able:true, visible: true, key: 'viewType' },
  { label: `属性代码`, able:true, visible: true, key: 'attrCode' },
  { label: `属性名称`, able:true, visible: true, key: 'attrName' },
	{ label: `字典类型`, able:true, visible: true, key: 'dictType' },
	{label: `是否择偶标准`, able: true, visible: true, key: 'isStandard'},
	{ label: `排序`, able:true, visible: true, key: 'sort' },
  { label: `创建者`, able:false, visible: false, key: 'createBy' },
  { label: `创建时间`, able:false, visible: false, key: 'createTime' },
  { label: `更新者`, able:false, visible: false, key: 'updateBy' },
  { label: `更新时间`, able:false, visible: false, key: 'updateTime' },
  { label: `备注`, able:true, visible: true, key: 'remark' },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    params:{},
    attrType: 'auth',
    viewType: null,
    attrCode: null,
    attrName: null,
		dictType: null,
    sort: null,
  },
  rules: {
	  viewType: [{ required: true, message: "显示类型不能为空", trigger: "blur" }],
	  attrCode: [{ required: true, message: "属性代码不能为空", trigger: "blur" }],
	  attrName: [{ required: true, message: "属性名称不能为空", trigger: "blur" }],
	  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],

  }
});

const { queryParams, form, rules } = toRefs(data);

function tabClick(p, e) {
	queryParams.value.attrType = p.props.name
	queryParams.value.pageNum = 1
	getList();
}
/** 显示类型示例 */
function handleViewExample() {
	visible.value = true;
}

/** 列显隐 */
function columnVisible(key) {
	return proxy.checkColumn(columns.value, key);
}

/** 查询用户属性配置列表 */
function getList() {
  loading.value = true;
  listUmAttrConf(queryParams.value).then(response => {
    umAttrConfList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    attrType: queryParams.value.attrType,
    viewType: null,
    attrCode: null,
    attrName: null,
		dictType: null,
    sort: null,
		isStandard: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
	  dictTypeDisable: true,
  };
  proxy.resetForm("umAttrConfRef");
}

/** 改变显示类型 */
const isDictTypeArray = ref(['select','radio','checkbox']);
function viewTypeChange(){
	if (isDictTypeArray.value.indexOf(form.value.viewType) > -1){
		form.value.dictTypeDisable = false
	}else {
		form.value.dictType = null
		form.value.dictTypeDisable = true
	}
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户属性配置";
  isInsert.value = true;
  isEdit.value = false;
}

/** 查看按钮操作 */
function handleView(row) {
  isEdit.value = false;
  title.value = "查看用户属性配置";
  getInfo(row);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  isEdit.value = true;
  title.value = "修改用户属性配置";
  getInfo(row);
}

function getInfo(row) {
  reset();
  const _id = row.id || ids.value
  isInsert.value = false;
  proxy.modal.loading("加载中");
  getUmAttrConf(_id).then(response => {
    form.value = response.data;
    open.value = true;
	  viewTypeChange()
    proxy.modal.closeLoading();
  }).catch(err=>{
    Promise.reject(err);
    proxy.modal.closeLoading();
  });
}

/** 提交按钮 */
const umAttrConfRef = ref(null)
function submitForm() {
  umAttrConfRef.value.validate(valid => {
    if (valid) {
	    if (isDictTypeArray.value.indexOf(form.value.viewType) > -1 && !form.value.dictType) {
		    proxy.modal.msgError("请选择字典类型");
				return;
	    }
		    if (form.value.id != null) {
        proxy.modal.loading("提交中");
        updateUmAttrConf(form.value).then(response => {
          proxy.modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          proxy.modal.closeLoading();
        }).catch(err=>{
          proxy.modal.closeLoading();
          Promise.reject(err);
        });
      } else {
        proxy.modal.loading("提交中");
        addUmAttrConf(form.value).then(response => {
          proxy.modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          proxy.modal.closeLoading();
        }).catch(err=>{
          proxy.modal.closeLoading();
          Promise.reject(err);
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.modal.confirm('是否确认删除用户属性配置编号为"' + _ids + '"的数据项？').then(function() {
    proxy.modal.loading("删除中");
    return delUmAttrConf(_ids);
  }).then(() => {
    getList();
    proxy.modal.msgSuccess("删除成功");
    proxy.modal.closeLoading();
  }).catch(() => {
    proxy.modal.closeLoading();
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download.post('um/umAttrConf/export', {
    ...queryParams.value
  }, `umAttrConf_${new Date().getTime()}.xlsx`)
}

/** 状态修改  */
const conditionAbleType = ['inputNumber','select','radio','checkbox']
function handleStatusChange(row, key,textFail = "停用",textSuc = "启用") {
	if (conditionAbleType.indexOf(row.viewType) > -1){

	let text = row[key] ? textFail : textSuc;
	proxy.modal.confirm('确认要【' + text + '】"' + row.attrName + '"数据项吗?').then(function () {
		return updateUmAttrConf({id: row.id, [key]: row[key]});
	}).then(() => {
		proxy.modal.msgSuccess(text + "成功");
	}).catch(function () {
		row[key] = row[key] ? 0 : 1;
	});
	}else {
		row[key] = row[key] ? 0 : 1;
		proxy.modal.msgError("此项不能开启为择偶标准(仅限数字输入、单选框、下拉框、复选框)");
	}
};

/** 查询字典下拉列表 */
const dictOptions = ref([]);
optionselect().then(response => {
	dictOptions.value = response.data;
});


getList();
</script>
